package com.ibm.sc.osp.sample.api.controller;

import com.ibm.sc.osp.common.response.RestResponse;
import com.ibm.sc.osp.common.utils.excel.ExportExcel;
import com.ibm.sc.osp.common.utils.excel.ImportExcel;
import com.ibm.sc.osp.sample.domain.entity.Message;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;

@RestController
public class DemoController {
    @RequestMapping(value = "/import")
    @ResponseBody
    //excel读取文件数据示例
    public ResponseEntity excelImport() {
        try {
            ImportExcel excel = new ImportExcel(new File("../demo.xls"), 0);
            return RestResponse.createSuccessRes(excel.getCellValue(excel.getRow(0), 0));
        } catch (Exception e) {
            LoggerFactory.getLogger(this.getClass()).error(e.getMessage());
        }
        return RestResponse.createFailRes();
    }
    
    @RequestMapping(value = "/export")
    @ResponseBody
    //excel创建文件示例
    public ResponseEntity excelExport() {
        try {
            ExportExcel excel = new ExportExcel("title", Arrays.asList("first", "second"));
            excel.addCell(excel.addRow(), 0, "test");
            excel.writeFile("../test.xls");
            excel.dispose();
            return RestResponse.createSuccessRes();
        } catch (Exception e) {
            LoggerFactory.getLogger(this.getClass()).error(e.getMessage());
        }
        return RestResponse.createFailRes();
    }
    
    @Resource
    private RestTemplate restTemplate;
    
    @RequestMapping(value = "/rest", method = RequestMethod.POST)
    @ResponseBody
    @HystrixCommand
    public ResponseEntity<RestResponse> rest(@RequestParam("url") String url) {
        try {
            //RestTemplate使用example
            return RestResponse.createSuccessRes(this.restTemplate.getForObject(url, Message.class));
        } catch (Exception e) {
            return RestResponse.createFailRes(e.getMessage());
        }
    }
}
